<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-10-18
 * Time: 下午4:53
 * 用户登录
 */
namespace Api\Home;

use Common\HttpStatus;
use Common\JsonApi;
use Common\Request;
use Common\RequestApi;
use Common\Response;
use Common\ResponseApi;
use DB\Home\AccountUser;
use DB\Token;

class PlutoLoginRequest extends RequestApi{
  public $account;
  public $password;
  public $device;
  public $deviceInfo;
}

class PlutoLoginResponse extends ResponseApi{
  public $uid;
  public $token;
}

class PlutoLogin extends JsonApi {
  protected function run(Request $request, Response $response) {
    /**
     * @var $rqData PlutoLoginRequest
     */
    $rqData = $request->data;
    if (empty($rqData->account)){
      $response->httpStatus = HttpStatus::PARAMETER_ERROR;
      $response->httpMessage = "account is not set";
      return;
    }
    if (empty($rqData->password)){
      $response->httpStatus = HttpStatus::PARAMETER_ERROR;
      $response->httpMessage = "password is not set";
      return;
    }

    $user = new AccountUser();
    if(!$user->buildByEmail($rqData->account)){
      $response->httpStatus = HttpStatus::AUTH_ERROR;
      $response->httpStatus = "account is not exists";
      return;
    }
    if (!$user->validatePwd($rqData->password)){
      $response->httpStatus = HttpStatus::AUTH_ERROR;
      $response->httpMessage = "password is error";
      return;
    }

    $token = new Token();
    $uid = (string)$user->getId();
    $token->initByUid($uid,$rqData->device??0);
    $response->data = new PlutoLoginResponse();
    $response->data->uid = $uid;
    $response->data->token = $token->getToken();
  }
}